package com.cjt.security;

import cn.hutool.core.util.StrUtil;
import com.cjt.common.exception.CaptchaException;
import com.cjt.common.lang.Const;
import com.cjt.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class CaptchaFilter extends OncePerRequestFilter {

    @Autowired
    LoginFailureHandler loginFailureHandler;
    @Autowired
    RedisUtil redisUtil;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String URI = request.getRequestURI();
        if (URI.equals("/login") && request.getMethod().equals("POST")) {
            //校验验证码
            try {
                checkCode(request);
            } catch (CaptchaException e) {
                //如果不正确 则给到登录失败处理器处理
                loginFailureHandler.onAuthenticationFailure(request, response, e);
            }
        }
        //如果不是login链接 = 放行
        filterChain.doFilter(request,response);
    }

    private void checkCode(HttpServletRequest request) {
        String code = request.getParameter("code");
        String key = request.getParameter("token");
        if (StrUtil.isBlank(code) || StrUtil.isBlank(key) ) {
            throw new CaptchaException("验证码错误");
        }
        if (!code.equals(redisUtil.hget(Const.CAPTCHA_KEY, key))){
            throw new CaptchaException("验证码错误");
        }
        redisUtil.hdel(Const.CAPTCHA_KEY,key);

    }
}
